<?php
namespace App\Service\ApiXcx;

use Illuminate\Support\Facades\DB;

class CardService extends BaseService
{
    //商品

    /**
     * 分类列表
     * @return array
     */
    public function getCateList()
    {
        $db = DB::table($this->dbCardCate)
            ->where('del', 0);
        $res = $db->get()
            ->map(function ($value){
                return (array)$value;
            })
            ->toArray();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => []);
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res);
    }

    /**
     * 礼品卡列表
     * @param array $pages【start，limit】
     * @param int $cateid 分类ID
     * @return array
     */
    public function getCardList($pages, $cateid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = DB::table($this->dbCard)->where('del', 0);
        if ($cateid) {
            $db = $db->where('cate_id', $cateid);
        }
        $total = $db->count();
        $db = $db->skip($start)->take($pages['limit']);

        $res = $db->get()->map(function ($value){
            return (array)$value;
        })
            ->toArray();
        foreach ($res as &$item) {
            $item['img_url'] = env('DOMAIN') . '/' . $item['img_url'];
        }
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => $total);
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
    }

    /**
     * 礼品卡列表
     * @param array $pages【start，limit】
     * @param int $cateid 分类ID
     * @return array
     */
    public function getMyCardList($pages, $uid, $status)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
//        $db = DB::table($this->dbCardUser)->where('del', 0)->where('uid', $uid);
//        if ($status == 1) { //可使用
//            $db = $db->where('is_used', 0)->where('is_transfer', 0);
//        }
//        if($status == 2){ //已使用
//            $db = $db->where('is_used', 1)->where('is_transfer', 0);
//        }
//        if($status == 3){ //已转增：已领取+赠送中
//            $db = $db->where('is_transfer', 1);
//        }
        $db = DB::table($this->dbCardUser);
        $ws[] = ['del', '=', 0];
        if ($status == 1) { //可使用
            $ws[] = ['uid', '=', $uid];
            $ws[] = ['is_used', '=', 0];
            $ws[] = ['is_transfer', '=', 0];
            $db = $db->where($ws);
        } else if ($status == 2){ //已使用
            $ws[] = ['uid', '=', $uid];
            $ws[] = ['is_used', '=', 1];
            $db = $db->where($ws);
        } else if ($status == 3){ //已转增：已领取+赠送中
            $ws[] = ['uid', '=', $uid];
            $ws[] = ['is_transfer', '=', 1];
            $db = $db->where($ws);
        } else {
            $ws[] = ['uid', '=', $uid];
            $db = $db->where($ws);
        }
        $total = $db->count();
        $db = $db->skip($start)->take($pages['limit']);
        $res = $db->orderBy('id', 'desc')
            ->get()->map(function ($value){
                return (array)$value;
            })
            ->toArray();
        if (!count($res)) {
            return array('code' => 0, 'msg' => '没有数据', 'data' => [], 'total' => $total);
        }
        foreach ($res as &$card) {
            $card_info = DB::table($this->dbCard)->where('id', $card['card_id'])->first();
            $cgOne = (array) $this->dbConn($this->dbCardGoods)->where('id', $card['card_goods_id'])->first();
            $card['title'] = $card_info->title.'【';
            if (!empty($cgOne)) {
                $card['title'] .= $cgOne['title'];
            }
            //$card['title'] .= '|' . substr($card['code'], -4);
            $card['title'] .= '】';
            $card['img_url'] = env('DOMAIN') . '/' . $card_info->img_url;
            if($status == 3) {
                $trans_card_info = DB::table($this->dbCardUser)
                    ->where('card_goods_id', $card['card_goods_id'])
                    ->where('from_id', $card['id'])
                    ->first();
                if($trans_card_info){
                    $card['trans_status'] = 1; //已领取
                }else{
                    $card['trans_status'] = 0; //0转增中
                }
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $res, 'total' => $total);
    }

    //礼品卡详情
    public function getCardOne($id)
    {
        $arys['id'] = $id;
        //卡片详情
        $cOne = (array) DB::table($this->dbCard)->where('id', $id)->where('del', 0)->first();
        if (!empty($cOne)) {
            $arys['title'] = $cOne['title'];
            $arys['img_url'] = env('DOMAIN') . '/' . $cOne['img_url'];
        }
        //卡片图片
        $cImgs = DB::table($this->dbCardImg)->where('del', 0)->where('card_id', $id)->get();
        if (count($cImgs)) {
            foreach ($cImgs as $v) {
                $v = (array) $v;
                $arys['imgs'][] = env('DOMAIN') . '/' . $v['link'];
            }
        }
        //卡片产品
        $goodsOnes = DB::table($this->dbCardGoods)->where('del', 0)->where('card_id', $id)->get();
        if (count($goodsOnes)) {
            foreach ($goodsOnes as $v) {
                $v = (array) $v;
                $arys['goodsList'][] = [
                    'goods_id' => $v['id'],
                    'title' => $v['title'],
                    'img_url' => env('DOMAIN') . '/' . $v['img_url'],
                    'code' => $v['code'],
                    'price' => $v['price'] / 100,
                    'stock' => $v['stock'],
                ];
            }
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys);
    }

    //使用页面
    public function useInfo($id, $uid)
    {
        $card_user_info = DB::table($this->dbCardUser)
            ->where('id', $id)
            ->where('del', 0)
            ->first();
        if(!$card_user_info){
            return array('code' => -2, 'msg' => '该卡片关联用户不存在');
        }
        if($card_user_info->uid != $uid){
            return array('code' => -2, 'msg' => '您没有购买该卡片');
        }
        if($card_user_info->is_used == 1 || $card_user_info->is_transfer == 1) {
            return array('code' => -2, 'msg' => '该卡片已使用或已转赠');
        }
        $card_goods_info = DB::table($this->dbCardGoods)
            ->where('id', $card_user_info->card_goods_id)
            ->where('del', 0)
            ->first();
        if(!$card_goods_info){
            return array('code' => -2, 'msg' => '该卡片产品不存在');
        }
        $card_info = DB::table($this->dbCard)->where('id',$card_goods_info->card_id)->where('del', 0)->first();
        if(!$card_info){
            return array('code' => -2, 'msg' => '该卡片不存在');
        }
        $return = [
            'img_url' => env('DOMAIN') . '/' . $card_info->img_url,
            'title' => $card_goods_info->title,
            //'code' => $card_goods_info->code,
            'code' => $card_user_info->code,
            'num' => $card_user_info->num
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $return);
    }

//    // 兑换
//    public function exchange($code, $uid)
//    {
//        $card_goods_info = DB::table($this->dbCardGoods)->where('code', $code)->where('del', 0)->first();
//        if(!$card_goods_info){
//            return array('code' => -2, 'msg' => '该卡片产品不存在');
//        }
//        $card_user_info = DB::table($this->dbCardUser)
//            ->where('card_goods_id', $card_goods_info->id)
//            ->where('uid', $uid)->where('del', 0)
//            ->first();
//        if(!$card_user_info){
//            return array('code' => -2, 'msg' => '您尚未购买该卡片');
//        }
////        if($card_user_info->is_used == 1 || $card_user_info->is_transfer == 1) {
////            return array('code' => -2, 'msg' => '该卡片已使用或已转赠');
////        }
//        DB::beginTransaction(); //开启事务
//        try {
//            DB::table($this->dbCardUser)->where('id', $card_user_info->id)->update(['is_used' => 1]);
//            DB::table($this->dbUser)->where('id', $card_user_info->uid)->increment('balance', ($card_goods_info->price*$card_user_info->num));
//            DB::commit(); //提交事务
//            return array('code'=>0, 'msg'=>'success');
//        } catch (\Exception $e) {
//            DB::rollBack(); //事务回滚
//            echo $e->getMessage();
//            return array('code'=>-1, 'msg'=>'操作失败');
//        }
//    }

    // 兑换
    public function exchange($code, $uid)
    {
        $cuOne = (array) DB::table($this->dbCardUser)
            ->where('code', $code)
            ->where('uid', $uid)
            ->where('del', 0)
            ->first();
        if (empty($cuOne)) {
            return $this->toback(-2, '还没购买此卡');
        }
        DB::beginTransaction(); //开启事务
        try {
            DB::table($this->dbCardUser)->where('id', $cuOne['id'])->update(['is_used' => 1]);
            DB::table($this->dbUser)
                ->where('id', $cuOne['uid'])
                ->increment('balance', ($cuOne['price'] * $cuOne['num']));
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }

    //领取的详情页面
    public function cardGoodsInfo($id){
        $card_user_info = DB::table($this->dbCardUser)->where('id', $id)->where('del', 0)->first();
        if(!$card_user_info){
            return array('code' => -2, 'msg' => '该卡片关联用户不存在');
        }
        $card_goods_info = DB::table($this->dbCardGoods)->where('id', $card_user_info->card_goods_id)->where('del', 0)->first();
        if(!$card_goods_info){
            return array('code' => -2, 'msg' => '该卡片产品不存在');
        }
        $card_info = DB::table($this->dbCard)->where('id', $card_goods_info->card_id)->where('del', 0)->first();
        if(!$card_info){
            return array('code' => -2, 'msg' => '该卡片不存在');
        }
        $user_info = DB::table($this->dbUser)->where('id', $card_user_info->uid)->where('del', 0)->first();
        if(empty($user_info)){
            return array('code' => -2, 'msg' => '卡片赠送人不存在');
        }
        $return = [
            'img_url' => env('DOMAIN') . '/' . $card_info->img_url,
            'title' => $card_goods_info->title,
            'code' => $card_goods_info->code,
            'price' => $card_goods_info->price,
            'phone' => $user_info->phone,
            'num' => $card_user_info->num
        ];
        return array('code' => 0, 'msg' => 'success', 'data' => $return);
    }

//    //卡片领取
//    public function receive($id, $uid){
//        $card_user_info =  DB::table($this->dbCardUser)->where('id', $id)->where('del', 0)->first();//原卡片信息
//        if(!$card_user_info){
//            return array('code' => -2, 'msg' => '该卡片关联用户不存在');
//        }
//        if($card_user_info->uid == $uid){
//            return array('code' => -2, 'msg' => '不可以领取自己的卡片');
//        }
//        if($card_user_info->is_used == 1){
//            return array('code' => -2, 'msg' => '该卡片已被使用');
//        }
//        $receive_info =  DB::table($this->dbCardUser)->where('from_id', $id)->where('del', 0)->first();
//        if($receive_info){
//            return array('code' => -2, 'msg' => '该卡片已被领取');
//        }
//        $card_goods_info = DB::table($this->dbCardGoods)->where('id', $card_user_info->card_goods_id)->where('del', 0)->first();
//        if(!$card_goods_info){
//            return array('code' => -2, 'msg' => '该卡片产品不存在');
//        }
//        $card_info = DB::table($this->dbCard)->where('id',$card_goods_info->card_id)->where('del', 0)->first();
//        if(!$card_info){
//            return array('code' => -2, 'msg' => '该卡片不存在');
//        }
//        DB::beginTransaction(); //开启事务
//        try {
//            $insert_data = [
//                'uid' => $uid,
//                'card_id' => $card_user_info->card_id,
//                'card_goods_id' => $card_user_info->card_goods_id,
//                'price' => $card_user_info->price,
//                'from_id' => $card_user_info->id,
//                'code' => $card_user_info->code,
//                'num' => $card_user_info->num,
//                'addtime' => toDate(),
//                'uptime' => toDate(),
//            ];
//            DB::table($this->dbCardUser)->insertGetId($insert_data);
//            DB::commit(); //提交事务
//            return array('code'=>0, 'msg'=>'success');
//        } catch (\Exception $e) {
//            DB::rollBack(); //事务回滚
//            echo $e->getMessage();
//            return array('code'=>-1, 'msg'=>'操作失败');
//        }
//    }

//    // 发送
//    public function share($id, $uid)
//    {
//        $card_goods_info = DB::table($this->dbCardGoods)
//            ->where('id', $id)
//            ->where('del', 0)
//            ->first();
//        if(!$card_goods_info){
//            return array('code' => -2, 'msg' => '该卡片产品不存在');
//        }
//        $card_user_info = DB::table($this->dbCardUser)->where('card_goods_id', $card_goods_info->id)->where('uid', $uid)->where('del', 0)->where('from_id', 0)->first();
//        if(!$card_user_info){
//            return array('code' => -2, 'msg' => '您尚未购买该卡片');
//        }
//        if($card_user_info->is_used == 1 || $card_user_info->is_transfer == 1) {
//            return array('code' => -2, 'msg' => '该卡片已使用或已转赠');
//        }
//        DB::table($this->dbCardUser)->where('id', $card_user_info->id)->update(['is_transfer' => 1]);
//        return array('code'=>0, 'msg'=>'success');
//    }

    // 发送
    public function share($id, $uid)
    {
        $cardOne = (array) DB::table($this->dbCardUser)
            ->where('id', $id)
            ->where('del', 0)
            ->first();
        if(empty($cardOne)){
            return $this->toback(-2, '该卡片不存在');
        }
        if($cardOne['is_used'] == 1 || $cardOne['is_transfer'] == 1) {
            return $this->toback(-2, '该卡片已使用或已转赠');
        }
        DB::table($this->dbCardUser)->where('id', $id)
            ->update(['is_transfer' => 1]);
        return $this->toback();
    }

    //卡片领取
    public function receive($id, $uid)
    {
        $cardOne = (array) DB::table($this->dbCardUser)
            ->where('id', $id)->where('del', 0)
            ->first(); //原卡片信息
        if(empty($cardOne)){
            return array('code' => -2, 'msg' => '该卡片关联用户不存在');
        }
        if($cardOne['uid'] == $uid){
            return array('code' => -2, 'msg' => '不可以领取自己的卡片');
        }
        if($cardOne['is_used'] == 1){
            return array('code' => -2, 'msg' => '该卡片已被使用');
        }
        $receive_info =  DB::table($this->dbCardUser)->where('from_id', $id)->where('del', 0)->first();
        if($receive_info){
            return array('code' => -2, 'msg' => '该卡片已被领取');
        }
        DB::beginTransaction(); //开启事务
        try {
            $insert_data = [
                'uid' => $uid,
                'card_id' => $cardOne['card_id'],
                'card_goods_id' => $cardOne['card_goods_id'],
                'price' => $cardOne['price'],
                'from_id' => $cardOne['id'],
                'code' => $cardOne['code'],
                'num' => $cardOne['num'],
                'addtime' => toDate(),
                'uptime' => toDate(),
            ];
            DB::table($this->dbCardUser)->insertGetId($insert_data);
            DB::commit(); //提交事务
            return array('code'=>0, 'msg'=>'success');
        } catch (\Exception $e) {
            DB::rollBack(); //事务回滚
            echo $e->getMessage();
            return array('code'=>-1, 'msg'=>'操作失败');
        }
    }
}